package proxy;


import java.lang.reflect.Type;
import java.util.Map;

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import configuration.SpringContextUtil;

/**
 * class RemoteRequestProxy
 *
 * @author alex
 * @version 0.1
 * @since 2017 12/13/17
 */
public class RemoteRequestProxy implements IRequestProxy {

    /**
     * 远程调用
     */
    private RestTemplate restTemplate;

    public RemoteRequestProxy(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }


    @Override
    public <T> T get(String url, Map<Object, ?> params, Map<Object, ?> urlParams, Type type) {
        StringBuffer sb = new StringBuffer("?");
        params.forEach((m, n) -> {
            sb.append(m + "=" + n + "&");
        });
        ResponseEntity<String> entity = restTemplate.getForEntity(url + sb.toString(), String.class);
        return SpringContextUtil.getValue(entity.getBody(), type);
    }

    @Override
    public <T> T post(String url, Map<Object, ?> params, Map<Object, ?> urlParams, Type type) {
        StringBuffer sb = new StringBuffer("?");
        params.forEach((m, n) -> {
            sb.append(m + "=" + n + "&");
        });
        ResponseEntity<String> entity = restTemplate.postForEntity(url + sb.toString(), params, String.class);
        return SpringContextUtil.getValue(entity.getBody(), type);
    }


    @Override
    public void del(String url, Map<Object, ?> params) {
        restTemplate.delete(url, params);
    }
}
